import usart from "@ohos.multimedia.usart";
const str_port = 0;
function test_open(){
    var res= usart.isOpen(str_port);
    if (res){
        console.info("[Wang] /dev/ttyAMA0 is open");
    }
    else{
        console.error("[Wang] /dev/ttyAMA0 is NOT OPEN !!!");
    }
    return res;
}

function Uint8ArrayToString(fileData){
    var dataString = "";
    for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
    }

    return dataString
}


function stringToUint8Array(str){
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
        arr.push(str.charCodeAt(i));
    }

    var tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array
}

var sleep = function(time) {
    var startTime = new Date().getTime() + parseInt(time, 10);
    while(new Date().getTime() < startTime) {}
};

export default {
    onStart(want) {
        console.info('[Wang] ServiceAbility onStart');
    },
    onStop() {
        console.info('[Wang] ServiceAbility onStop');
    },
    onConnect(want) {
        console.info('[Wang] ServiceAbility onConnect');
        return {};
    },
    onReconnect(want) {
        console.info('[Wang] ServiceAbility onReconnect');
    },
    onDisconnect() {
        console.info('[Wang] ServiceAbility onDisconnect');
    },
    onCommand(want, restart, startId) {
        console.info('[Wang] ServiceAbility onCommand');

        if(usart == null){
            console.error("[Wang] usart module is not loaded !!!");
        }
        else{
            console.info("[Wang] usart module is loaded");
            console.info(usart.toString());
            console.info("usart.open is " + usart.open.toString())
        }
        console.info("[Wang] trying to open /dev/ttyAMA0");
        usart.open(str_port);
        test_open();
        console.info("[Wang] begin reading");
        var i = 5
        while(i--){
            if(!usart.isOpen(str_port)){
                console.error("[Wang] /dev/ttyAMA0 is NOT OPEN !!!");
            }
            //一次读一行
            var read_res_as_u8array=usart.readline(str_port);
//            var read_res_as_string=Uint8ArrayToString(read_res_as_u8array);
//            console.info({wang_read: read_res_as_string})
            console.info("readline end!");
            sleep(2000); // 延时函数，单位ms
        }
    }
};